<!--  -->
<template>
  <div class="main">
    <div class="flex-top">
      <p class="title">运营指标数据监控 </p>
      <div class="items">
          <span class="item" :class="activeName == 'all'? 'selected' : ''" @click="toSelected('all')">整体概览</span>
          <span class="item" :class="activeName == 'peer'? 'selected' : ''" @click="toSelected('peer')">
            <el-dropdown trigger="click" placement='bottom' @visible-change='arrowChange'>
              <span class="el-dropdown-link item"  :class="activeName == 'peer'? 'selected' : ''">
                技能组<i class="el-icon-arrow-down" :class="arrow ? 'up' : ''"></i>
              </span>
              <el-dropdown-menu slot="dropdown" >
                  <Select :list="selectedQueue" @select='selectQueue' @search='getPeerIds'></Select>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
          <span class="item" :class="activeName == 'access'? 'selected' : ''" @click="toSelected('access')">
            <el-dropdown trigger="click" placement='bottom' @visible-change='arrowChange'>
              <span class="el-dropdown-link item"  :class="activeName == 'access'? 'selected' : ''">
                接入号<i class="el-icon-arrow-down" :class="arrow ? 'up' : ''"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                  <Select toValue='accessId' :list="channelList" @select='selectQueue' @search='getAccessIds'></Select>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
      </div>
    </div>
    <section class="mysection">
      <div class="section-top">
        <OperationalIndicator  :data="indexData"/>
      </div>
      <p class="section-title">在线座席监控</p>
      <div class="section-bottom">
        <quickSearch   :advForm="quickSearchForm" @QuickSearch='handleCurrentChange(false, true)'></quickSearch>
        <div class="straightLine"></div>
        <Table :tableHeaders="tableHeaders" :tableData="tableData"  ref="myTable"></Table>
        <el-pagination
        class="pages"
        @current-change="handleCurrentChange"
        @size-change="handleCurrentChange"
        :current-page.sync="pagingData.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pagingData.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagingData.total"
      >
      </el-pagination>
      </div>
    </section>
  </div>
</template>

<script lang='ts'>
import io from 'socket.io-client';
import { Component, Vue } from 'vue-property-decorator'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import { commonAction, deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common/index'
import Select from './components/select.vue'
import Table from './components/table.vue'
import { ReportModule } from '@/store/modules/report'
import OperationalIndicator from './components/operationalIndicator.vue'
// import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
interface Satisfaction {
    name: string,
    key: string
}
@Component({
  name: 'OnlineMonitoring',
  components: { quickSearch, Select, Table, OperationalIndicator }
})

export default class extends Vue {
  private h = this.$createElement
  private $store
  private $getCache
  private activeName = 'all'
  private quickSearchForm: any = {
    // 快捷检索数据（时间条件，类型）
    form: {
      agentName: '', // 座席名称
      agentStatus: [], // 座席状态列表
      queueList: [] // 技能组列表
    },

    advSearchOptions: [] // 初始化选项
  }

  private pagingData = {
    limit: 10,
    page: 1,
    total: 0
  }

  private arrow = false
  private arrowChange (flag) {
    console.log(flag)
    this.arrow = flag
  }

  private handleCurrentChange (val?: any, flag?: boolean) {
    const { agentName, agentStatus, queueList } = this.quickSearchForm.form
    const data = this.allData.filter(item => {
      const agentFlag = agentStatus.length ? agentStatus.includes(item.currentClaimStatus) : true
      const queueFlag = queueList.length ? item.queueList.filter(v => queueList.includes(v)).length : true
      return item.agentName.includes(agentName) && agentFlag && queueFlag
    })

    this.pagingData.total = data.length
    const list: any = []
    if (flag) {
      this.pagingData.page = 1
    }
    const { limit, page, total } = this.pagingData
    for (let i = (page - 1) * limit; i < page * limit; i++) {
      const element = data[i]
      if (element) {
        list.push(element)
      }
    }
    this.tableData = list
  }

  private allData: any = []
  private indexData = {}
  private toSelected (item) {
    this.activeName = item
    if (item === 'all') {
      this.getData()
    }
  }

  private channelList: any = []
  private getChannelList () {
    this.$getCache('/im-center/action/webchat/channelCache', ['channelList'], true).then(res => {
      if (res.success) {
        this.channelList = deepClone(res.channelList)
        this.channelList.forEach(i => {
          i.selected = false
        });
      }
    })
  }

  get queueList () {
    return CommonModule.publicCache.queueList
  }

  private async created () {
    this.getChannelList()
    const list = deepClone(CommonModule.publicCache.queueList)
    list.forEach(i => {
      i.selected = false
    });
    this.selectedQueue = list
    await this.getSatisfactionList()
    await this.getStateList()
    setTimeout(() => {
      this.tableHeaderInit()
    }, 200)
    this.quickSearchForm.advSearchOptions = [
      { label: '技能组', inputType: 'select', selectData: this.queueList, name: 'queueList', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'name', value: '_id' } },
      { label: '座席名称', inputType: 'input', placeholder: '请输入座席名称', name: 'agentName', clearable: true },
      { label: '座席状态', inputType: 'select', selectData: this.stateList, name: 'agentStatus', filterable: true, multiple: true, clearable: true, defaultProp: { label: 'name', value: '_id' } }
    ]
  }

  get websocketUrl () {
    return (CommonModule.initConfig as any).pushServer.monitorUrl
  }

  private timer = 0
  private socket: any = 0
  private socketData: any
  private getLink () {
    const data = {
      transport: 'websocket',
      logintoken: CommonModule.session.user && CommonModule.session.user.loginToken ? CommonModule.session.user.loginToken : '',
      sessionid: this.$store.state.common.session.user._id
    }
    const socketData = { reconnectionDelay: 3000, query: data }
    this.socketData = socketData
    socketData['force new connection'] = true
    let url = this.websocketUrl
    if (window.location.host.indexOf('localhost') > -1) { // 本地代理https环境还是http环境，自己修改
      url = `wss://${this.websocketUrl}`
    }
    const emitData = {
      sessionType: this.activeName,
      peerIds: this.peerIds,
      accessIds: this.accessIds
    }
    const socket = io(url, socketData)
    this.socket = socket
    socket.on('monitor', (q, m) => {
      if (m?.hasOwnProperty('agentMonitor')) {
        this.tableDataInit(m.agentMonitor)
        this.indexData = m.sessionMonitor
      }
    })
    socket.emit('monitor', 'imMonitor', emitData)
    this.timer = setInterval(() => {
      socket.emit('monitor', 'imMonitor', emitData)
    }, 3000)
  }

  private deactivated () {
    clearInterval(this.timer)
    this.timer = -1
    this.socket.close()
  }

  private activated () {
    this.getLink()
  }

  private getData () {
    clearInterval(this.timer)
    const emitData = {
      sessionType: this.activeName,
      peerIds: this.peerIds,
      accessIds: this.accessIds
    }

    this.socket.emit('monitor', 'imMonitor', emitData)
    this.timer = setInterval(() => {
      this.socket.emit('monitor', 'imMonitor', emitData)
    }, 3000)
  }

  private peerIds = []
  private accessIds = []
  private getPeerIds (list) {
    this.peerIds = list
    this.getData()
  }

  private getAccessIds (list) {
    this.accessIds = list
    this.getData()
  }

  private selectedQueue = []
  private selectQueue (item, i) {
    console.log(item, i)
  }
  // 满意度

  private satisfactionList: Satisfaction[] = []
  private satisfactionHeader: any = []
  private async getSatisfactionList () {
    await ReportModule.getSatisfactionList().then(res => {
      if (res) {
        this.satisfactionList = res.filter(i => i.isUse)
        this.satisfactionList.forEach(i => {
          this.satisfactionHeader.push({
            prop: i.key,
            label: i.name + '(占比)'
          })
        })
      }
    })
  }

  // 在线自定义状态
  private stateList = []
  private stateMap = new Map()
  private stateHeader: any = []
  private async getStateList () {
    await ReportModule.getStateList().then(res => {
      if (res) {
        this.stateList = res
        const map = new Map()
        res.forEach(i => {
          this.stateHeader.push({
            prop: i._id,
            label: i.name + '状态累计时长'
          })
          map.set(i._id, i)
        })

        this.stateMap = map
      }
    })
  }

  // table
  private tableHeaders: any = []
  private tableData: any = []
  private tableHeaderInit () {
    function getColor (row, that) {
      if (row.currentClaimStatus === 'offline') {
        return '#BABDC3'
      }
      if (that.stateMap.get(row.currentClaimStatus)?.status === 'open') {
        return '#008BEE'
      } else {
        return '#FC6B5C'
      }
    }
    const name = (row) => {
      if (row.currentClaimStatus === 'offline') {
        return '离线'
      } else {
        return this.stateMap.get(row.currentClaimStatus)?.name
      }
    }
    let tableHeaders: any = [
      { label: '座席姓名', prop: 'agentName', fixed: 'left' },
      {
        label: '当前状态(时长)',
        prop: 'currentStatusTime',
        formatter: (row) => {
          const h = this.$createElement

          return h('div', {
            class: 'mylist'
          },
          [
            h('i', {
              class: 'V7_iconfont V7_iconV7tubiao_dian',
              style: `color: ${getColor(row, this)}`
            }),
            `${name(row)} (${row.currentStatusTime})`
          ])
        },
        width: '200'
      },
      { label: '当前接待量/最大', prop: 'validCount', formatter: (row) => `${row.currentImDealCount}/${row.currentMaxImDealCount}` },
      { label: '累计会话量', prop: 'initCount' },
      { label: '平均首响', prop: 'avgFirstReplyLen', formatter: (row) => `${row.avgFirstReplyLen}s` },
      { label: '平均响应', prop: 'avgMsgResponseLen', formatter: (row) => `${row.avgMsgResponseLen}s` },
      { label: '参评率', prop: 'evaluateRate' },
      { label: '邀评率', prop: 'pushCsrRate' }
    ]
    tableHeaders = tableHeaders.concat(this.stateHeader, this.satisfactionHeader)
    this.tableHeaders = tableHeaders
  }

  private tableDataInit (data) {
    console.log(this.$refs.myTable)
    const list: any = []
    data.forEach(element => {
      list.push(Object.assign({}, element, element.agentClaimStatusTime, element.evaluateDataRate))
    })
    // this.tableData = list
    this.allData = list
    this.pagingData.total = list.length
    this.handleCurrentChange()
  }
}
</script>
<style lang='stylus' scoped>
.main
  padding-top 8px
  height 100%
  border-radius 10px
  box-sizing border-box
.title
  font-size 14px
  height 30px
  line-height 30px
  font-family PingFang SC
  font-weight 600
  color #303753
.mysection
  height calc(100% - 48px)
  background #FFFFFF
  box-shadow 0px 0px 4px 0px #E0E6F0, 0px 1px 4px 0px #E0E6F0
  border-radius 10px
  padding 24px 16px
  margin 2px
  box-sizing: border-box;
  overflow auto
.section-title
  height: 14px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 600;
  color: #303753;
  line-height: 14px;
  margin-top 24px
  margin-bottom 15px
.flex-top
  display flex
  justify-content: space-between
  margin-bottom 16px
  .items
    width: 218px;
    height: 30px;
    background: #EFF3F8;
    border-radius: 4px;
    position relative
    padding 2px
    // &::before
    //   content ''
    //   width 70px
    //   height 26px
    //   background: #FFFFFF;
    //   z-index 1
    //   left 2px
    //   position absolute

    .item
      display inline-block
      position relative
      width 70px
      height 26px
      line-height 26px
      text-align center
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #767E91;
      cursor pointer
      z-index 2
    .selected
      color: #303753;
      background: #FFFFFF;
      border-radius: 4px;
      transition: all 0.8s;
      .el-icon-arrow-down.up
        transition: all 0.8s;
        transform: rotateX(180deg);
.pages
  text-align right
  margin-top 10px
.straightLine
  width 100%
  height: 1px;
  background: #ECF0F3;
  margin-bottom 16px;
  margin-top: -8px;
/deep/.el-pagination__total
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #767E91;
</style>
